// pages/order_detail/order_detail.js
var common = require("../../../common/common").common;

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        details: [],
        trade_no: "",
        code: "",
        show_code: 0,
        color_header: "",
        color_main: "",
        color_minor: "",
        is_open: 1,
        showDiscout: 0,
        lucky_member: "",
        status: "",
        rp_name: "",
        little_title: "",
        payBtn: false,
        componentStyle: {
            navigationTitle: "订单详情",
            goBack: 1
        },
        cancelBtn: false
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    /**details
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        wx.hideShareMenu();
        let pagesLength = getCurrentPages().length;
        var isIPX = app.globalData.isIPX;
        this.setData({
            isIPX: isIPX,
            domain: app.globalData.domain.slice(0, -10),
            componentStyle: {
                goBack: pagesLength
            }
        });
        console.log(options.status);
        this.setData({
            trade_no: options.trade_no,
            apply_status: options.status,
            level: options.level || "",
            esb_id: options.esb_id || ""
        });
        if (options.openid) {
            this.setData({
                openid: options.openid
            });
        }
        this.getBase();
        this.getData();
        this.discountOpen();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        let that = this;
        that.getData();
        that.discountOpen();
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {
        var that = this;
        var order_id = that.data.trade_no;
        var little_title = that.data.little_title;
        var lucky_member = that.data.lucky_member;
        return {
            title: little_title + "拼手气，第" + lucky_member + "个人领取的红包最大！",
            path: "/pages/lucky_discount/lucky_discount?order_id=" + order_id,
            imageUrl: that.data.luck_img
        };
    },
    index_call: function(e) {
        var phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    order_copy: function(e) {
        var copy = e.currentTarget.dataset.copy;
        wx.setClipboardData({
            data: copy,
            success: function(res) {
                wx.showToast({
                    title: "复制成功",
                    icon: "succes",
                    duration: 1e3,
                    mask: true
                });
            }
        });
    },
    getData: function() {
        var that = this;
        var openid;
        if (that.data.openid) {
            openid = that.data.openid;
        } else {
            openid = wx.getStorageSync("user").openid;
        }
        var trade_no = that.data.trade_no;
        // common.request({
        //   endpoint: 'Order/orderinfo/order_detail',
        //   method: 'post',
        //   data: {
        //     // openid: openid,
        //     trade_no: trade_no,
        //   },
        //   success: res => {
        //     console.log(res)
        //     that.setData({
        //       details: res.extra
        //     })
        //   }
        // })
                var params = {
            openid: openid,
            trade_no: trade_no,
            esb_id: that.data.esb_id
        };
        if (that.data.level) {
            params["level"] = that.data.level;
        }
        common.request({
            endpoint: "Order/orderinfo/order_detail2",
            method: "post",
            data: params,
            success: res => {
                let details = res.data;
                if (that.data.openid) {
                    details.user.order_phone = details.user.order_phone.substring(0, 3) + "****" + details.user.order_phone.substring(7);
                    details.user.order_name = details.user.order_name.replace(/([\u4E00-\u9FA5]{1})([\u4E00-\u9FA5]+)$/, "$1*****");
                }
                details.order.totoal_discount = (parseFloat(details.order.coupon_discount) + parseFloat(details.order.package_discount) + parseFloat(details.order.credit_discount)).toFixed(2);
                var total_packing_fee = 0;
                details.order_info.map(item => {
                    if (item.packing_fee) {
                        total_packing_fee += parseFloat(item.packing_fee).toFixed(2);
                    }
                });
                that.setData({
                    details: details
                });
            }
        });
    },
    cancel_order: function() {
        var that = this;
        var trade_no = that.data.trade_no;
        common.request({
            endpoint: "Order/orderinfo/cancel_order",
            method: "post",
            data: {
                trade_no: trade_no
            },
            success: res => {
                wx.showToast({
                    title: "取消成功",
                    icon: "success",
                    success: res => {
                        setTimeout(() => {
                            wx.switchTab({
                                url: "/pages/order/order"
                            });
                        }, 500);
                    }
                });
            }
        });
    },
    // showCode: function (e) {
    //   var that = this
    //   var trade_no = e.currentTarget.dataset.ddh;
    //   var openid = wx.getStorageSync('user').openid;
    //   common.request({
    //     endpoint: 'My/qrcode/getqrcode',
    //     method: 'post',
    //     data: {
    //       openid: openid,
    //       trade_no: trade_no,
    //     },
    //     success: res => {
    //       console.log(res)
    //        var array = wx.base64ToArrayBuffer(res.extra.png);
    //        var base64 = wx.arrayBufferToBase64(array); 
    //       that.setData({
    //         code: "data:image/png;base64," + base64,
    //         show_code: 1,
    //       })
    //     }
    //   })
    // },
    showCode: function(e) {
        var that = this;
        var trade_no = e.currentTarget.dataset.ddh;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/qrcode/getqrcode",
            method: "post",
            data: {
                openid: openid,
                trade_no: trade_no
            },
            success: res => {
                console.log(res);
                var array = wx.base64ToArrayBuffer(res.png);
                var base64 = wx.arrayBufferToBase64(array);
                that.setData({
                    code: "data:image/png;base64," + base64,
                    show_code: 1
                });
            }
        });
    },
    closeCode: function() {
        this.setData({
            show_code: 0
        });
    },
    pay: function(e) {
        let that = this;
        //禁用立即支付按钮
                that.setData({
            payBtn: true
        });
        var trade_no = e.currentTarget.dataset.ddh;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "order/pay",
            method: "post",
            data: {
                openid: openid,
                order_num: trade_no
            },
            success: res => {
                console.log(res);
                wx.requestPayment({
                    timeStamp: res.extra.timeStamp,
                    nonceStr: res.extra.nonceStr,
                    package: res.extra.package,
                    signType: res.extra.signType,
                    paySign: res.extra.paySign,
                    success: function(res) {
                        console.log(res);
                        wx.showToast({
                            title: "支付成功",
                            icon: "success",
                            mask: true,
                            duration: 3e3,
                            success: function(res) {
                                wx.showToast({
                                    title: "购买成功！",
                                    icon: "success",
                                    success: function() {
                                        common.request({
                                            endpoint: "Order/common/sync-notify",
                                            method: "post",
                                            data: {
                                                order_no: trade_no
                                            },
                                            success: res => {
                                                setTimeout(function() {
                                                    wx.switchTab({
                                                        url: "/pages/order/order"
                                                    });
                                                }, 500);
                                            }
                                        });
                                    },
                                    fail(err) {
                                        wx.showModal({
                                            title: "提示",
                                            content: err.message
                                        });
                                    }
                                });
                            }
                        });
                    },
                    fail: function(res) {
                        wx.switchTab({
                            url: "/pages/order/order"
                        });
                    },
                    complete: function(res) {}
                });
            },
            fail: function(res) {
                wx.showModal({
                    title: "提示",
                    content: res.message,
                    success() {
                        wx.switchTab({
                            url: "/pages/order/order"
                        });
                    }
                });
            }
        });
    },
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                var componentStyle = that.data.componentStyle;
                that.setData({
                    componentStyle: {
                        ...componentStyle,
                        color_minor: !res.extra.color_main ? "#FE513B" : res.extra.color_main,
                        color_minor: !res.extra.color_minor ? "#FE513B" : res.extra.color_minor
                    },
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    is_open: res.extra.is_open,
                    rp_name: res.extra.rp_name,
                    luck_img: res.extra.luck_img,
                    refund_control: res.extra.refund_control ? res.extra.refund_control : "1",
                    user_refund_control: res.extra.refund_control ? res.extra.user_refund_control : "1",
                    after_time: res.extra.after_time,
                    little_title: res.extra.title,
                    leader_detail_edit: res.extra.leader_detail_edit,
                    leader_refund_else: res.extra.leader_refund_else,
                    user_refund_else: res.extra.user_refund_else,
                    leader_phone_button: res.extra.leader_phone_button,
                    special_custom_name: res.extra.special_custom_name
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
            }
        });
    },
    showDiscount: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var order_id = that.data.trade_no;
        console.log(order_id);
        common.request({
            endpoint: "Voucher/luckyvou/sendvoucher",
            method: "post",
            data: {
                order_id: order_id,
                openid: openid
            },
            success: res => {
                that.setData({
                    lucky_member: res.extra.lucky_member,
                    showDiscount: 1
                });
            }
        });
    },
    closeDiscount: function() {
        this.setData({
            showDiscount: 0
        });
    },
    discountOpen: function() {
        var that = this;
        common.request({
            endpoint: "Voucher/luckyvou/isoff",
            method: "post",
            success: res => {
                that.setData({
                    status: res.extra.status
                });
            }
        });
    },
    onPageScroll(e) {
        var scrollTop = e.scrollTop;
        if (!scrollTop) {
            this.setData({
                componentOpcity: 0
            });
        } else if (scrollTop / 44 >= 1) {
            this.setData({
                componentOpcity: 1
            });
        } else {
            this.setData({
                componentOpcity: scrollTop / 44
            });
        }
    },
    goBack() {
        wx.navigateBack({});
    },
    toCancelOrder() {
        let that = this;
        if (that.data.is_open == 0) {
            wx.showModal({
                title: "提示",
                content: "休市期间无法进行退款处理，请联系平台管理员!",
                showCancel: false
            });
            return;
        }
        // let ids=[];
        // let order_info = this.data.details.order_info;
        // order_info.map(x=>{
        //   ids.push(x.id);
        // })
                wx.navigateTo({
            url: "/pages/cancel_order/cancel_order?info=" + encodeURIComponent(JSON.stringify(this.data.details))
        });
    },
    /**
   * 休市无法申请退款
   */
    applyRefund(e) {
        let that = this;
        if (that.data.is_open == 0) {
            wx.showModal({
                title: "提示",
                content: "休市期间无法进行退款售后，请联系平台管理员!",
                showCancel: false
            });
            return;
        }
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    }
});